/*
 * JOAQUÍN RAMÓN ANTÚNEZ SÁNCHEZ
 * 17 de septiembre de 2014
 * 
 */

package mon;

import java.util.HashMap;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
import javax.swing.JOptionPane;

@SuppressWarnings({"rawtypes", "unchecked"})
public class jr{
	
	private static Connection con = null;
	private static jr instance = null;
	
	private void error(String msg){
		String s = String.format("El servidor MySQL nos comunica el siguiente error:\n\"%s\".\n", msg);
		JOptionPane.showMessageDialog(null, s, "¡ERROR", JOptionPane.ERROR_MESSAGE );
	}
	
	
	public static Connection cursor(){ return con; }
	
	public static jr get(){
		if( instance == null ){
			instance = new jr();
		}
		
		return instance;
	}
	
	private jr(){
		try{
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection("jdbc:mysql://localhost", "root", "2629buruaz");
		}
		catch(Exception e){
			
		}
	}
	
	
	public void close(){
		if( con == null ){
			try{ con.close(); }
			catch(Exception e){}
		}
		instance = null;
	}
	
	public ArrayList<HashMap> execute(String query){
		Statement st = null;
		ArrayList<HashMap> l = null;
		
		try{
			st = con.createStatement();
			ResultSet rs =  st.executeQuery(query);
			if( null != rs ){
				ResultSetMetaData data = rs.getMetaData();
				while( rs.next() ){
					HashMap map = new HashMap();
					for( int x = 1; x <= data.getColumnCount(); x++){
						String name = data.getColumnName(x).toLowerCase();
						if( data.getColumnType(x) == java.sql.Types.SMALLINT )
							map.put(name, rs.getInt(name));
						else
							map.put(name, rs.getObject(x) == null ? "" : rs.getString(x));
					}
					if( null == l ) l = new ArrayList<HashMap>();
					l.add(map);
				}
				rs.close();
				rs = null;
			}
			
			st.close();
			st = null;
		}
		catch(Exception e){ this.error(e.getMessage()); }
		
		return l;
	}
	
	public int inc(String tabla, String condicion /*=null*/){
		
		String query = String.format("Select distinct max(id) as id from %s%s", 
				tabla, condicion == null ? "" : "\nwhere " + condicion);
		
		try{
			int x = 0;
			Statement st = con.createStatement();
			ResultSet rs = st.executeQuery(query);
			if( null != rs ){				
				if( rs.absolute(1) ){
					x = rs.getInt(1);
				}
				x++;
				rs.close();
				rs = null;				
			}
			
			st.close();
			return x;
		} 
		catch(Exception e){
			return 0;
		}
	}	
	
	@SuppressWarnings("static-access")
	public static int exec(String sql){
		int rows = 0;
		jr j = jr.get();
		try{
			PreparedStatement ps = j.cursor().prepareStatement(sql);
			rows = ps.executeUpdate();
			ps.close();
			ps = null;
		}
		catch(Exception e){  }
		
		j.close();
		
		return rows;
	} 
	
	
}
